package se.rende.schema2ical.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaveSchemaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("SaveSchemaServlet.doGet()");
		PrintWriter w = resp.getWriter();
		resp.setContentType("text/plain");
		w.write("hej!");
		w.close();
		resp.setStatus(200);
	}
	
	/**
	 * Saves the posted test to /home/xxx/.schema2ical/save.json
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("SaveSchemaServlet.doPost()");
		String userHome = System.getProperty("user.home");
		if (userHome != null) {
			try {
				File saveDir = new File(userHome, ".schema2ical");
				saveDir.mkdirs();
				File saveFile = new File(saveDir, "save.json");
				PrintWriter pw = new PrintWriter(new FileWriter(saveFile));
				BufferedReader r = req.getReader();
				while (true) {
					String line = r.readLine();
					if (line == null) {
						break;
					}
					System.out.println("SaveSchemaServlet.doPost() line=" + line);
					pw.println(line);
				}
				pw.close();
				resp.setStatus(200);
			} catch (IOException e) {
				System.err.println(e);
				resp.setStatus(500);
			}
		} else {
			System.err.println("system property user.home=" + userHome);
			resp.setStatus(500);
		}
	}
}
